package com.itheima.controller;

import com.itheima.domain.Admin;
import com.itheima.domain.User;
import com.itheima.service.AdminService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;

    @GetMapping("/login")
    public String showLoginForm() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, Model model, HttpSession session) {
        // 1. 尝试普通用户登录
        User user = userService.userLogin(username, password);
        if (user != null) {
            session.setAttribute("user", user); // 将用户存入session
            return "redirect:/home";
        }

        // 2. 尝试管理员登录
        Admin admin = adminService.authenticate(username, password);
        if (admin != null) {
            session.setAttribute("admin", admin); // 将管理员存入session
            return "redirect:/dashboard";
        }

        // 3. 检查用户是否存在
        User isExit = userService.findUserByName(username);
        Admin adminExist = adminService.findAdminByUsername(username);

        if (isExit == null && adminExist == null) {
            // 既不是用户也不是管理员
            model.addAttribute("error", "无此用户，请先注册！");
        } else if (adminExist != null) {
            // 是管理员但密码错误
            model.addAttribute("error", "管理员密码错误！");
        } else {
            // 是用户但密码错误
            model.addAttribute("error", "用户名或密码错误，请重试！");
        }

        return "login";
    }

    @GetMapping("/register")
    public String showRegisterForm() {
        return "register";
    }

    @PostMapping("/register")
    public String register(User user, Model model, RedirectAttributes redirectAttributes) {
        String resultRegister = userService.userRegister(user);
        if (resultRegister == null) {
            redirectAttributes.addFlashAttribute("successRegister", "注册成功，请登录！");
            return "redirect:/login";
        } else {
            model.addAttribute("errorMsg", resultRegister);
            return "register";
        }
    }

    @GetMapping("/update")
    public String showUpdateForm(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        model.addAttribute("user", user);
        return "update";
    }

    @PostMapping("/update")
    public String update(HttpSession session, User user, Model model, RedirectAttributes redirectAttributes) {
        User user1 = (User) session.getAttribute("user");
        user.setUserId(user1.getUserId());
        String updateResult = userService.userUpdate(user);
        if (updateResult == null) {
            User user2 = userService.findUserById(user1.getUserId());
            session.setAttribute("user", user2);
            redirectAttributes.addFlashAttribute("trueMsg", "修改信息成功！");
            return "redirect:/update";
        } else {
            model.addAttribute("errorMsg", updateResult);
        }
        return "update";
    }

    @RequestMapping("logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }


    @PostMapping("/uploadAvatar")
    public String uploadAvatar(@RequestParam("avatar") MultipartFile file,
                               HttpSession session,
                               RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("errorMessage", "请选择要上传的头像!");
            return "redirect:/userCenter";
        }

        // 获取当前登录用户
        User user = (User) session.getAttribute("user");

        try {
            // 上传目录路径
            String uploadDir = "D:/CBSystem/userPictures/" + user.getUserId() + "/";


            // 如果目录不存在则创建
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //有则删除
            if (user.getAvatar() != null) {
                File oldFile = new File(uploadDir + user.getAvatar());
                if (oldFile.exists()) {
                    oldFile.delete();
                }
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + fileExtension;

            // 保存文件
            File dest = new File(uploadDir + newFilename);
            file.transferTo(dest);

            // 更新用户头像路径
            user.setAvatar(newFilename);
            userService.updateAvatar(user.getUserId(), newFilename);

            // 更新session中的用户信息
            session.setAttribute("user", user);

            redirectAttributes.addFlashAttribute("successMessage", "头像上传成功!");
        } catch (IOException e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "头像上传失败!");
        }

        return "redirect:/userCenter";
    }
}
